import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { setValueWithLocalStorage } from '@/utils/authority';
import { channelLogin } from '@/services/http';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'channelLogin',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const {callback} =  payload
      const response = yield call(channelLogin, payload);
      callback(response)
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.code == 1) {
        reloadAuthorized();
        window.location.href = '/channelerhome';
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setValueWithLocalStorage('userinfo',payload.ret);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
